<script lang="ts">
import {defineComponent} from 'vue'
import DialogAndBlock from "@/components/DialogAndBlock/index.vue";
import {ElMessage} from "element-plus";
import fileReq from "@/api/file";
import pathBrowserify from "path-browserify";
import {ClipboardUtils} from "@/utils/clipboardUtils";
import {ClickCopy} from "@/directive/ClickCopy";
import {ShareFile} from "@/entityType/ShareFile";

export default defineComponent({
  name: "ShareFile",
  components: {DialogAndBlock},
  directives: {
    ClickCopy
  },
  data() {
    return {
      basePath: '',
      shareFiles:[] as ShareFile[],
    }
  },
  methods: {
    open(basePath:string, fileNames:string[]) {
      this.basePath = basePath
      this.shareFiles = fileNames.map(i=>{
        return {
          fileName: i,
          fullPath: '',
          entTime: ''
        }
      })
      this.$refs.DialogRef.open()
    },
    shareClick() {
      if (this.shareFiles.find(i=>!i.entTime)) {
        ElMessage.error('结束时间不能为空')
        return
      }
      let shareFiles = this.shareFiles.map(i=>{
        return {
          ...i,
          filePath: pathBrowserify.resolve(this.basePath, i.fileName)
        }
      })
      fileReq.shareFileOrDir(shareFiles).then(res => {
        (res.data as string[]).forEach((id,index)=>{
          this.shareFiles[index].fullPath = location.origin + location.pathname + '/#/showShareFile/' + id
        })
        if(this.shareFiles.length === 1) {
          ClipboardUtils.copyToClipboard(this.shareFiles[0].fullPath).then(res=>{
            ElMessage.success('分享链接已复制到剪切板')
          }).catch(err=>{
            ElMessage.error(err)
          })
        } else {
          ElMessage.success('分享完成')
        }
      })
    },
  }
})
</script>

<template>
  <DialogAndBlock
    ref="DialogRef"
    title="文件分享"
  >
    <div v-for="(item,index) in shareFiles" :key="'shareFiles'+index">
      <div>分享的文件：{{ item.fileName }}</div>
      <div>
        <el-button
          text
          type="success"
          icon="copyDocument"
          v-click-copy="item.fullPath"
        >
          分享的链接：{{ item.fullPath }}
        </el-button>
      </div>
      <div style="margin-top: 20px;margin-bottom: 20px;">
        <el-date-picker
          v-model="shareFiles[index].entTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择结束时间"
        />
      </div>
    </div>
    <div style="text-align: right">
      <el-button
        type="primary"
        @click.stop="shareClick"
      >
        分享
      </el-button>
    </div>
  </DialogAndBlock>
</template>

<style scoped lang="scss">

</style>
